﻿using System;
using System.Data;
using System.Windows.Forms;
using Google.GData.Analytics;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using System.Collections.Generic;

namespace SSISComponents
{
    public partial class frmGoogleAnalyticsSource : Form
    {
        #region Variables

        /// <summary>
        /// Component Parameter
        /// </summary>

        const int MaxPreviewRows = 200;
        const string AppName = "SSIS GoogleAnalyticsSource";
        
        private string _profileId = null;
        private string _Username = null;
        private string _Password = null;
        private string _StartDate = null;
        private string _EndDate = null;
        //private string _StartIndex = null;
        //private string _MaxResults = null;
        private string _Dimensions = null;
        private string _Metrics = null;
        private string _DefaultSegments = null;
        //private string _DimensionsFilter = null;
        //private string _MetricsFilter = null;

        private AnalyticsService Service = null;
        private GoogleMetrics gaMet = null;
        private GoogleDimensions gaDim = null;
        private DataFeed feed = null;

        private IDTSComponentMetaData100 _dtsComponentMetadata;
        private IServiceProvider _service;
        private Variables _variables;
        private Connections _connections;
        private Boolean _Login = false;

        #endregion Variables

        #region Properties

        string ProfileID
        {
            set
            {
                _profileId = value;
                cbbProfile.SelectedValue = _profileId;
            }
            get
            {
                try
                {
                    return cbbProfile.SelectedValue.ToString();
                }
                catch { return null; }
            }
        }

        string Username
        {
            set
            {
                _Username = value;
                this.txtUsername.Text = value;
            }
            get
            {
                _Username = this.txtUsername.Text;
                return _Username;
            }
        }

        string Password
        {
            set
            {
                _Password = value;
                this.txtPassword.Text = value;
            }
            get
            {
                _Password = this.txtPassword.Text;
                return _Password;
            }
        }

        string StartDate
        {
            set
            {
                _StartDate = value;
                this.dtpStartDate.Text = value;
            }
            get
            {
                _StartDate = dtpStartDate.Value.ToString("yyyy-MM-dd");
                return _StartDate;
            }
        }

        string EndDate
        {
            set
            {
                this.dtpEndDate.Text = value;
                _EndDate = value;
            }
            get
            {
                _EndDate = dtpEndDate.Value.ToString("yyyy-MM-dd");
                return _EndDate;
            }
        }

        ///StartIndex ist not using at the moment
        //string StartIndex
        //{
        //    set
        //    {
        //        this.nudStartIndex.Text = value;
        //        _StartIndex = value;
        //    }
        //    get
        //    {
        //        _StartIndex = this.nudStartIndex.Text;
        //        return _StartIndex;
        //    }
        //}

        ///MaxResults is not using at the moment
        //string MaxResults
        //{
        //    set
        //    {
        //        this.nudMaxResults.Text = value;
        //        _MaxResults = value;
        //    }
        //    get
        //    {
        //        _MaxResults = this.nudMaxResults.Text;
        //        return _MaxResults;
        //    }
        //}

        string Dimensions
        {
            set
            {
                string[] arrDimension = value.Split('|');
                int index = 0;
                int[] arrCount = new int[arrDimension.Length];
                int iCounter = 0;
                foreach (DataRowView view in clbDimension.Items)
                {
                    for (int i = 0; i <= arrDimension.Length - 1; i++)
                    {
                        if (view[clbDimension.ValueMember].ToString() == arrDimension[i])
                        {
                            arrCount[iCounter] = index;
                            iCounter++;
                        }
                    }
                    index++;
                }
                for (int i = 0; i <= arrCount.Length - 1; i++)
                {
                    clbDimension.SetItemChecked(arrCount[i], true);
                }

            }
            get
            {
                string tempDimensions = null;
                int intDim = 0;
                foreach (DataRowView view in clbDimension.CheckedItems)
                {
                    intDim += 1;
                    tempDimensions += view[clbDimension.ValueMember].ToString();
                    if (intDim < clbDimension.CheckedItems.Count) tempDimensions += "|";
                }
                _Dimensions = tempDimensions;
                return _Dimensions;
            }
        }

        string Metrics
        {
            set
            {
                string[] arrMetrics = value.Split('|');
                int index = 0;
                int[] arrCount = new int[arrMetrics.Length];
                int iCounter = 0;
                foreach (DataRowView view in clbMetrics.Items)
                {
                    for (int i = 0; i <= arrMetrics.Length - 1; i++)
                    {
                        if (view[clbMetrics.ValueMember].ToString() == arrMetrics[i])
                        {
                            arrCount[iCounter] = index;
                            iCounter++;
                        }
                    }
                    index++;
                }
                for (int i = 0; i <= arrCount.Length - 1; i++)
                {
                    clbMetrics.SetItemChecked(arrCount[i], true);
                }
            }
            get
            {
                string tempMetrics = null;
                int intMetrics = 0;
                foreach (DataRowView view in clbMetrics.CheckedItems)
                {
                    intMetrics += 1;
                    tempMetrics += view[clbMetrics.ValueMember].ToString();
                    if (intMetrics < clbMetrics.CheckedItems.Count) tempMetrics += "|";
                }
                _Metrics = tempMetrics;
                return _Metrics;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        string DefaultSegments
        {
            set
            {
                try
                {
                    if (value == null)
                    {
                        clbDefaultSegments.SelectedValue = "gaid::-1";
                    }
                    else
                    {
                        clbDefaultSegments.SelectedValue = value;
                    }
                }
                catch (Exception ex)
                {
                }
            }
            get
            {
                try
                {
                    _DefaultSegments = clbDefaultSegments.SelectedValue.ToString();
                }
                catch (Exception ex) { }
                return _DefaultSegments;
            }
        }

        #endregion Properties

        #region Initialize

        /// <summary>
        ///
        /// </summary>
        /// <param name="dtsComponentMetadata"></param>
        /// <param name="serviceProvider"></param>
        /// <param name="variables"></param>
        /// <param name="connections"></param>
        public frmGoogleAnalyticsSource(IDTSComponentMetaData100 dtsComponentMetadata, IServiceProvider serviceProvider, Variables variables, Connections connections)
        {
            InitializeComponent();
            _dtsComponentMetadata = dtsComponentMetadata;
            _service = serviceProvider;
            _variables = variables;
            _connections = connections;
        }

        #endregion Initialize

        #region GUI Functions

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (Metrics != null && Dimensions != null)
            {
                
                //this._profileId = cbbProfile.SelectedValue.ToString();
                Connect(txtUsername.Text.ToString(), txtPassword.Text.ToString());
                //cbbProfile.SelectedValue = this._profileId;

                DataQuery query = new DataQuery(SSISComponents.GoogleAnalyticsSource.dataFeedUrl);
                query.Ids = ProfileID;
                query.Filters = GoogleAnalytics.FilterCombine(GetDimensionsFilter(false), GetMetricsFilter(false));
                query.Metrics = Metrics.Replace("|", ",");
                query.Dimensions = Dimensions.Replace("|", ",");
                query.Segment = DefaultSegments.Replace("|", ",");
                query.GAStartDate = dtpStartDate.Value.ToString("yyyy-MM-dd");
                query.GAEndDate = dtpEndDate.Value.ToString("yyyy-MM-dd");
                query.NumberToRetrieve = MaxPreviewRows;
                
                try
                {
                    frmPreview frmP = new frmPreview();
                    frmP.dtgaData = GoogleAnalytics.AsDataTable(Service.Query(query), query);
                    frmP.ShowDialog();
                }

                catch(Exception ex)
                {
                    frmCustomError frmCE = new frmCustomError();
                    frmCE.PErrorText = ex.ToString();
                    frmCE.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("Please specify at least one Metric and one Dimension.", "SSIS GoogleAnalyticsSource", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }





        /// <summary>
        /// Checks the connection to GoogleAnalytics
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                //this._profileId = cbbProfile.SelectedValue.ToString();
                Connect(txtUsername.Text.ToString(), txtPassword.Text.ToString());
                //cbbProfile.SelectedValue = this._profileId;
                MessageBox.Show("Connection is successful!");
            }
            catch
            {
                MessageBox.Show("Connection could not be established!");
            }
        }

        /// <summary>
        /// Connect to GoogleAnalytics on leaving the username textbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                Connect(txtUsername.Text.ToString(), txtPassword.Text.ToString(), false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmGoogleAnalyticsSource_Load(object sender, EventArgs e)
        {
            gaDim = new GoogleDimensions();
            clbDimension.DataSource = gaDim.Dimensions;
            clbDimension.DisplayMember = "Name";
            clbDimension.ValueMember = "APIName";

            gaMet = new GoogleMetrics();
            clbMetrics.DataSource = gaMet.Metrics;
            clbMetrics.DisplayMember = "Name";
            clbMetrics.ValueMember = "APIName";

            if (_dtsComponentMetadata.CustomPropertyCollection["Username"].Value != null)
            {
                Username = _dtsComponentMetadata.CustomPropertyCollection["Username"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["Password"].Value != null)
            {
                Password = _dtsComponentMetadata.CustomPropertyCollection["Password"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["StartDate"].Value != null)
            {
                StartDate = _dtsComponentMetadata.CustomPropertyCollection["StartDate"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["EndDate"].Value != null)
            {
                EndDate = _dtsComponentMetadata.CustomPropertyCollection["EndDate"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["Dimensions"].Value != null)
            {
                Dimensions = _dtsComponentMetadata.CustomPropertyCollection["Dimensions"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["DimensionsFilter"].Value != null)
            {
                SetDimensionFilter(_dtsComponentMetadata.CustomPropertyCollection["DimensionsFilter"].Value.ToString());
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["Metrics"].Value != null)
            {
                Metrics = _dtsComponentMetadata.CustomPropertyCollection["Metrics"].Value.ToString();
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["MetricsFilter"].Value != null)
            {
                SetMetricsFilter(_dtsComponentMetadata.CustomPropertyCollection["MetricsFilter"].Value.ToString());
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["Username"].Value != null
                && _dtsComponentMetadata.CustomPropertyCollection["Password"].Value != null)
                //&& _dtsComponentMetadata.CustomPropertyCollection["Profile"].Value != null)
            {
                Connect(txtUsername.Text.ToString(), txtPassword.Text.ToString(), false);
                if (_dtsComponentMetadata.CustomPropertyCollection["Profile"].Value != null)
                {
                    ProfileID = _dtsComponentMetadata.CustomPropertyCollection["Profile"].Value.ToString();
                }
            }

            if (_dtsComponentMetadata.CustomPropertyCollection["DefaultSegments"].Value != null)
            {
                DefaultSegments = _dtsComponentMetadata.CustomPropertyCollection["DefaultSegments"].Value.ToString();
            }

            SetCBMetricsFilter();
            SetCBDimensionFilter();
        }

        /// <summary>
        /// Add selected Dimensions to the DimensionFilter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clbDimension_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetCBDimensionFilter();
            DataRowView dv = (DataRowView)clbDimension.SelectedItem;
            txtDimDescription.Text = gaDim.GetDescription(dv["APIName"].ToString());
        }

        /// <summary>
        /// Add selected Metrics to the MetricsFilter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clbMetrics_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetCBMetricsFilter();
            DataRowView dv = (DataRowView)clbMetrics.SelectedItem;
            txtMetDescription.Text = gaMet.GetDescription(dv["APIName"].ToString());
        }

        /// <summary>
        /// Set the MetricsFilter ComboBox
        /// </summary>
        private void SetCBMetricsFilter()
        {
            DataTable MetricsFilter = new DataTable("MetricsFilter");
            DataColumn colName = new DataColumn("Name", System.Type.GetType("System.String"));
            MetricsFilter.Columns.Add(colName);
            DataColumn colValue = new DataColumn("APIName", System.Type.GetType("System.String"));
            MetricsFilter.Columns.Add(colValue);

            foreach (DataRowView view in clbMetrics.CheckedItems)
            {
                DataRow dr = MetricsFilter.NewRow();
                dr["Name"] = view[clbMetrics.DisplayMember].ToString();
                dr["APIName"] = view[clbMetrics.ValueMember].ToString();
                MetricsFilter.Rows.Add(dr);
            }

            this.cbMetricsFilter.DataSource = MetricsFilter;
            this.cbMetricsFilter.DisplayMember = "Name";
            this.cbMetricsFilter.ValueMember = "APIName";
        }

        /// <summary>
        /// Set the Dimension Filter ComboBox
        /// </summary>
        private void SetCBDimensionFilter()
        {
            DataTable DimensionFilter = new DataTable("DimensionFilter");
            DataColumn colName = new DataColumn("Name", System.Type.GetType("System.String"));
            DimensionFilter.Columns.Add(colName);
            DataColumn colValue = new DataColumn("APIName", System.Type.GetType("System.String"));
            DimensionFilter.Columns.Add(colValue);

            foreach (DataRowView view in clbDimension.CheckedItems)
            {
                DataRow dr = DimensionFilter.NewRow();
                dr["Name"] = view[clbDimension.DisplayMember].ToString();
                dr["APIName"] = view[clbDimension.ValueMember].ToString();
                DimensionFilter.Rows.Add(dr);
            }

            this.cbDimensionFilter.DataSource = DimensionFilter;
            this.cbDimensionFilter.DisplayMember = "Name";
            this.cbDimensionFilter.ValueMember = "APIName";
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDimensionFilter_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtDimensionFilter.Text))
            {
                MessageBox.Show("You must define an expression.", "Metrics Filter", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            dgvDimensionsFilter.Rows.Add(FilterRow(
                cbDimensionFilter.Text.ToString()
                , cbDimensionFilter.SelectedValue.ToString()
                , cbDimensionOperator.Text.ToString()
                , txtDimensionFilter.Text.ToString()
                ));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddMetricsFilter_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtMetricsFilter.Text))
            {
                MessageBox.Show("You must define an expression.", "Metrics Filter", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            dgvMetricsFilter.Rows.Add(FilterRow(
                cbMetricsFilter.Text.ToString()
                , cbMetricsFilter.SelectedValue.ToString()
                , cbMetricsOperator.Text.ToString()
                , txtMetricsFilter.Text.ToString()
                ));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvMetricsFilter_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex != dgvMetricsFilter.Columns["MetricsFilterDelete"].Index) return;
            dgvMetricsFilter.Rows.RemoveAt(e.RowIndex);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDimensionsFilter_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex != dgvDimensionsFilter.Columns["Delete"].Index) return;
            dgvDimensionsFilter.Rows.RemoveAt(e.RowIndex);
        }

        /// <summary>
        /// Check Valid Combination
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clbDimension_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                DataRowView dv = (DataRowView)clbDimension.SelectedItem;
                foreach (DataRowView view in clbMetrics.CheckedItems)
                {
                    if (gaDim.UnvalidMetrics(dv["APIName"].ToString(), view[clbMetrics.ValueMember].ToString()))
                    {
                        MessageBox.Show("The slected dimension \"" + dv["Name"].ToString() + "\" and selected metric \"" + view[clbMetrics.DisplayMember].ToString() + "\" are not valid combinations.", "SSIS GoogleAnalyticsSource", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.NewValue = CheckState.Unchecked;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Check Valid Combination
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clbMetrics_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                DataRowView dv = (DataRowView)clbMetrics.SelectedItem;
                foreach (DataRowView view in clbDimension.CheckedItems)
                {
                    if (gaDim.UnvalidMetrics(view[clbDimension.ValueMember].ToString(), dv["APIName"].ToString()))
                    {
                        MessageBox.Show("The slected dimension \"" + view[clbDimension.DisplayMember].ToString() + "\" and selected metric \"" + dv["Name"].ToString() + "\" are not valid combinations.", "SSIS GoogleAnalyticsSource", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.NewValue = CheckState.Unchecked;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Add GUI Values to Custom Property Collection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (Metrics == null || Dimensions == null || Username == null || Password == null || ProfileID == null)
            {
                if (MessageBox.Show("There are configuration errors. Do you want to fix it now?","SSIS GoogleAnalyticsSource",MessageBoxButtons.OKCancel,MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                {
                    this.DialogResult = DialogResult.Cancel;
                }
            }
            else
            {
                _dtsComponentMetadata.CustomPropertyCollection["Username"].Value = Username;
                _dtsComponentMetadata.CustomPropertyCollection["Password"].Value = Password;
                _dtsComponentMetadata.CustomPropertyCollection["Profile"].Value = ProfileID;
                _dtsComponentMetadata.CustomPropertyCollection["Dimensions"].Value = Dimensions;
                _dtsComponentMetadata.CustomPropertyCollection["Metrics"].Value = Metrics;
                _dtsComponentMetadata.CustomPropertyCollection["DefaultSegments"].Value = DefaultSegments;
                _dtsComponentMetadata.CustomPropertyCollection["StartDate"].Value = StartDate;
                _dtsComponentMetadata.CustomPropertyCollection["EndDate"].Value = EndDate;
                _dtsComponentMetadata.CustomPropertyCollection["MetricsFilter"].Value = GetMetricsFilter(true);
                _dtsComponentMetadata.CustomPropertyCollection["DimensionsFilter"].Value = GetDimensionsFilter(true);
                this.DialogResult = DialogResult.OK;
            }
        }

        #endregion GUI Functions

        #region Non GUI Functions

        /// <summary>
        /// Connect to GoogleAnalytics
        /// </summary>
        private void Connect(string Username, string Password)
        {
            Connect(Username, Password, true);
        }

        /// <summary>
        /// Connect to GoogleAnalytics
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <param name="RaiseError"></param>
        private void Connect(string Username, string Password, Boolean RaiseError)
        {
            if (_Login == false)
            {
                AccountQuery query = new AccountQuery();
                Service = new AnalyticsService("SSISGoogleAnalytics");
                if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                {
                    Service.setUserCredentials(Username, Password);
                }

                try
                {
                    SetProfile(ProfileDataTable(Service.Query(query)));
                    _Login = true;
                }
                catch (Exception ex)
                {
                    if (RaiseError == true)
                    {
                        MessageBox.Show("The connection could not be established." + ex.ToString(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    _Login = false;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void GetSegemnts()
        {
            try
            {
                if (cbbProfile.SelectedValue.ToString() != null && cbbProfile.SelectedValue.ToString() != "System.Data.DataRowView" && cbbProfile.SelectedValue.ToString().Substring(0,2).ToUpper() == "GA")
                {
                    AccountQuery query = new AccountQuery();
                    AccountFeed accountFeed = Service.Query(query);

                    if (accountFeed.Segments.Count > 0)
                    {
                        try
                        {
                            clbDefaultSegments.Items.Clear();
                        }
                        catch { }
                        SetSegment(SegmentsDataTable(accountFeed.Segments));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please connect to a valid account." + ex.ToString(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="AccountFeed"></param>
        private void SetProfile(DataTable AccountFeed)
        {
            cbbProfile.DataSource = AccountFeed;
            cbbProfile.ValueMember = "ID";
            cbbProfile.DisplayMember = "Name";
            cbbProfile.SelectedIndex = 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="AccountFeed"></param>
        private void SetSegment(DataTable Segment)
        {
            try
            {
                clbDefaultSegments.DataSource = Segment;
                clbDefaultSegments.ValueMember = "ID";
                clbDefaultSegments.DisplayMember = "Name";
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// Creates a row for the filter settings
        /// </summary>
        /// <param name="Name">Name of the Dimension/Metric</param>
        /// <param name="APIName">APIName of the Dimension/Metric</param>
        /// <param name="Operator">Filter Operator</param>
        /// <param name="Expression">Expression on Filter</param>
        /// <returns></returns>
        private DataGridViewRow FilterRow(string Name, string APIName, string Operator, string Expression)
        {
            DataGridViewRow row = new DataGridViewRow();
            DataGridViewTextBoxCell cFilter = new DataGridViewTextBoxCell();
            DataGridViewTextBoxCell cOperator = new DataGridViewTextBoxCell();
            DataGridViewTextBoxCell cExpression = new DataGridViewTextBoxCell();

            cFilter.Value = Name;
            cFilter.Tag = APIName;
            cOperator.Value = Operator;
            cExpression.Value = Expression;

            row.Cells.Add(cFilter);
            row.Cells.Add(cOperator);
            row.Cells.Add(cExpression);

            return row;
        }

        /// <summary>
        /// Build a DataTable with the current AccountFeed
        /// </summary>
        /// <param name="ac">Google Analytics AccountFeed</param>
        /// <returns></returns>
        private DataTable ProfileDataTable(AccountFeed ac)
        {
            DataTable dt = new DataTable("Profile");
            DataColumn colName = new DataColumn("Name", System.Type.GetType("System.String"));
            dt.Columns.Add(colName);
            DataColumn colID = new DataColumn("ID", System.Type.GetType("System.String"));
            dt.Columns.Add(colID);
            foreach (AccountEntry entry in ac.Entries)
            {
                DataRow dr = dt.NewRow();
                dr[0] = entry.Title.Text.ToString();
                dr[1] = entry.ProfileId.Value.ToString();
                dt.Rows.Add(dr);
            }
            return dt;
        }

        private DataTable SegmentsDataTable(List<Segment> segment)
        {
            DataTable dt = new DataTable("Profile");
            DataColumn colName = new DataColumn("Name", System.Type.GetType("System.String"));
            dt.Columns.Add(colName);
            DataColumn colID = new DataColumn("ID", System.Type.GetType("System.String"));
            dt.Columns.Add(colID);
            if (segment.Count > 0)
            {
                foreach (Segment s in segment)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = s.Name;
                    dr[1] = s.Id;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        /// <summary>
        /// Returns current metrics
        /// </summary>
        /// <returns></returns>
        //private string GetMetrics()
        //{
        //    string gaMetrics = null;
        //    int iMet = 0;
        //    foreach (DataRowView view in clbMetrics.CheckedItems)
        //    {
        //        if (iMet > 0) gaMetrics += ",";
        //        gaMetrics += view[clbMetrics.ValueMember].ToString();
        //        iMet++;
        //    }
        //    return gaMetrics;
        //}

        /// <summary>
        /// Returns current dimensions
        /// </summary>
        /// <returns></returns>
        //private string GetDimensions()
        //{
        //    string gaDimensions = null;
        //    int iDim = 0;
        //    foreach (DataRowView view in clbDimension.CheckedItems)
        //    {
        //        if (iDim > 0) gaDimensions += ",";
        //        gaDimensions += view[clbDimension.ValueMember].ToString();
        //        iDim++;
        //    }
        //    return gaDimensions;
        //}

        /// <summary>
        /// Returns current dimensions filter
        /// </summary>
        /// <returns></returns>
        private string GetDimensionsFilter(bool cpc)
        {
            string gaDimensionsFilter = "";
            int iDimFilter = 0;
            foreach (DataGridViewRow view in dgvDimensionsFilter.Rows)
            {
                if (cpc == true)
                {
                    gaDimensionsFilter += view.Cells["Dimension"].Value.ToString() + "|" + view.Cells["Dimension"].Tag.ToString() + "|" + view.Cells["Operator"].Value.ToString() + "|" + view.Cells["Expression"].Value.ToString() + ";";
                }
                else
                {
                    if (iDimFilter > 0) gaDimensionsFilter += ";";
                    gaDimensionsFilter += view.Cells["Dimension"].Tag.ToString() + view.Cells["Operator"].Value.ToString() + view.Cells["Expression"].Value.ToString();
                }
                iDimFilter++;
            }
            return gaDimensionsFilter;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="Filter"></param>
        private void SetDimensionFilter(string Filter)
        {
            string[] arrFilter = Filter.Split(';');
            for (int i = 0; i < arrFilter.Length - 1; i++)
            {
                string[] arrFilterRow = arrFilter[i].Split('|');
                if (arrFilterRow.Length != 4)
                {
                    MessageBox.Show("Invalid parameters were passed.");
                }
                else
                {
                    dgvDimensionsFilter.Rows.Add(FilterRow(arrFilterRow[0], arrFilterRow[1], arrFilterRow[2], arrFilterRow[3]));
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="Filter"></param>
        private void SetMetricsFilter(string Filter)
        {
            string[] arrFilter = Filter.Split(';');
            for (int i = 0; i < arrFilter.Length - 1; i++)
            {
                string[] arrFilterRow = arrFilter[i].Split('|');
                if (arrFilterRow.Length != 4)
                {
                    MessageBox.Show("Invalid parameters were passed.");
                }
                else
                {
                    dgvMetricsFilter.Rows.Add(FilterRow(arrFilterRow[0], arrFilterRow[1], arrFilterRow[2], arrFilterRow[3]));
                }
            }
        }

        /// <summary>
        /// Returns current metrics filter
        /// </summary>
        /// <returns></returns>
        private string GetMetricsFilter(bool cpc)
        {
            string gaMetricsFilter = "";
            int iMetricsFilter = 0;
            foreach (DataGridViewRow view in dgvMetricsFilter.Rows)
            {
                if (cpc == true)
                {
                    gaMetricsFilter += view.Cells["Metrics"].Value.ToString() + "|" + view.Cells["Metrics"].Tag.ToString() + "|" + view.Cells["MetricsOperator"].Value.ToString() + "|" + view.Cells["MetricsExpression"].Value.ToString() + ";";
                }
                else
                {
                    if (iMetricsFilter > 0) gaMetricsFilter += ";";
                    gaMetricsFilter += view.Cells["Metrics"].Tag.ToString() + view.Cells["MetricsOperator"].Value.ToString() + view.Cells["MetricsExpression"].Value.ToString();
                }
                iMetricsFilter++;
            }
            return gaMetricsFilter;
        }

        #endregion Non GUI Functions

        #region Info URLS

        /// <summary>
        /// Open http://AnalyticsSource.codeplex.com/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkCodeplex_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://bitly.com/dKNeC5?r=bb");
        }

        /// <summary>
        /// Open http://www.ssis-components.net/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkSSISComponents_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://bitly.com/aC8F6y?r=bb");
        }

        /// <summary>
        /// Open http://www.datenfabrik.com/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkDatenfabrik_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://bitly.com/iR6iCD?r=bb");
        }

        /// <summary>
        /// Open http://code.google.com/p/google-gdata/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkGoogleData_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://bitly.com/nFWsUy?r=bb");
        }

        /// <summary>
        /// Open http://www.apache.org/licenses/LICENSE-2.0
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkApacheLicense_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://bitly.com/pBX1kE?r=bb");
        }

        #endregion Info URLS

        private void cbbProfile_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetSegemnts();
        }



    }
}